package com.common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class AutoTestUtils {

    private static ChromeDriver driver;

    //创建驱动
    public static ChromeDriver getDriver() {
        if(driver == null) {
            driver = new ChromeDriver();
            //创建隐式等待，设置最长等待时间为10秒
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        }
        return driver;
    }

    /**
     * 获取屏幕截图，将用例执行结果保留下来
     * @param str
     * @throws IOException
     */
    public void getScreenShot(String str) throws IOException {
        List<String> list = getTime();
        String fileName = "./src/test/java/com/blogWebAutoTest/" + list.get(0) + "/" + str + "_" + list.get(1) + ".png";
        File srcFile = driver.getScreenshotAs(OutputType.FILE);
        //把生成的截图文件放入指定路径
        FileUtils.copyFile(srcFile, new File(fileName));
    }

    /**
     * 生成文件的保存时间
     * @return
     */
    private List<String> getTime() {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd-HHmmssSS");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        //当天的年月 + 具体时间
        String fileName = sdf1.format(System.currentTimeMillis());
        //当天的年月
        String dirName = sdf2.format(System.currentTimeMillis());
        List<String> list = new ArrayList<>();
        list.add(dirName);
        list.add(fileName);
        return list;
    }

}
